<?php
	function saveRecord($JsonData)
	{
		$selectDate = $JsonData->{"selectDate"};
		$walkSteps = $JsonData->{"walkSteps"};
		$powerExerciseNum = $JsonData->{"powerExerciseNum"};
		// connect to database
		$con = mysql_connect("localhost","wbpbfkvk_wp445","ljy890523");
		
		if ($con)
		{	
			$db_selected = mysql_select_db("wbpbfkvk_wp445", $con);
			$sql = "INSERT INTO  `wbpbfkvk_wp445`.`daily_info` (`walkSteps` ,`selectDate` ,`powerExerciseNum`)
				VALUES ('$walkSteps',  '$selectDate',  '$powerExerciseNum');";
			mysql_query($sql);
			mysql_close($con);
		}
		
		sendRecord("ServerSendRecord",$selectDate,$walkSteps,$powerExerciseNum);
	}

	function sendRecord($cmd,$selectDate,$walkSteps,$powerExerciseNum)
	{
		$arr['cmd'] = "ServerSendRecord"; 
		$arr['selectDate'] = $selectDate; 
		$arr['walkSteps'] = $walkSteps; 
		$arr['powerExerciseNum'] = $powerExerciseNum; 
		echo json_encode($arr);
	}
	
	function buildRecord($cmd,$selectDate,$walkSteps,$powerExerciseNum)
	{
		$arr['cmd'] = "ServerSendRecord"; 
		$arr['selectDate'] = $selectDate; 
		$arr['walkSteps'] = $walkSteps; 
		$arr['powerExerciseNum'] = $powerExerciseNum; 
		return $arr;
	}

	function queryDataBase($sql)
	{
		$con = mysql_connect("localhost","wbpbfkvk_wp445","ljy890523");
		
		if ($con)
		{	
			$myArray = array();
			$sql = "select * from daily_info";
			$db_selected = mysql_select_db("wbpbfkvk_wp445", $con);

			$result = mysql_query($sql);
			
			while ($row = mysql_fetch_array($result)) {
			
			$myArray[] = buildRecord("ServerSendRecord",$row["selectDate"],$row["walkSteps"],$row["powerExerciseNum"]);
			//	$i = $i +1;
				
			}

			echo json_encode($myArray);
			mysqli_close($con);
		}		
	}

	function parseCmd($data_back)
	{
		$cmd = $data_back->{"cmd"};
		switch ($cmd)
		{
			case "ClientApplyInsertRecord":
				saveRecord($data_back);
			break;

			case "ClientApplyQueryRecord":
				queryDataBase("hello");
			//sendRecord("ServerSendRecord","0","0","0");
			break;
		}
	}
	
	// read JSon input
	$data_back = json_decode(file_get_contents('php://input'));

	//saveRecord($data_back);
	parseCmd($data_back);
	
?>
